package com.groupbuying.redpacket.timer;

import com.alibaba.fastjson.JSON;
import com.groupbuying.redpacket.service.RedPacketListService;

import com.groupbuying.redpacket.websocket.StandingListWebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @ClassName StandingListTimer
 * @Description: TODO   定时任务（弃用）
 * @Author srlg3
 * @Date 2019/11/19
 * @Version V1.0
 **/
//@Component
public class StandingListTimer {
    Logger logger = LoggerFactory.getLogger(StandingListTimer.class);

    @Autowired
    private RedPacketListService redPacketListService;

    private Timer timer;

    /**
     * @MethodName: startTimer
     * @Description: TODO   开始启动定时任务
     * @param redPacketWebSocketServer   webSocket对象
     * @Author: srlg3
     * @Date: 2019/11/20
     */
    public void startTimer(StandingListWebSocketServer redPacketWebSocketServer){
        //因为webSocket是多例  所以每次都得创建一个新的
        timer = new Timer();
        logger.info("排名定时任务开始执行,任务id{}", redPacketWebSocketServer.getSid());
        //启动定时查询排行
        //定义计时器；
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                //调用启动逻辑
                List<Map<String, Object>> standing = redPacketListService.currentRankingRotation("1");

                //发送到前台
                try {
                    redPacketWebSocketServer.sendMessage(JSON.toJSONString(standing));
                } catch (IOException e) {
                    logger.error("排名定时任务执行,任务id{},错误提示：连接异常", redPacketWebSocketServer.getSid());
                    e.printStackTrace();
                }
            }
        },3000,3000);
        logger.error("排名定时任务执行结束,任务id{}", redPacketWebSocketServer.getSid());
    }

    /**
     * @MethodName: colseTimer
     * @Description: TODO   关闭定时任务
     * @Return: void
     * @Author: srlg3
     * @Date: 2019/11/20
     */

    public void colseTimer(){
        timer.cancel();
        logger.info("提示信息：关闭定时任务");
    }
}
